package com.service.schedule.tm;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.excel.EasyExcel;
import com.common.DateUtils;
import com.common.StringUtils;
import com.common.excel.EasyExcelCustomCellWriteHandler;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.dao.sys.FileDao;
import com.dao.sys.SysDao;
import com.dao.tm.PlanDao;
import com.enums.FactoryEnum;
import com.enums.SysRoleEnum;
import com.enums.TmPlanStatusEnum;
import com.model.sys.FileModel;
import com.model.tm.PlanModel;
import com.service.external.oa.CreateMailService;
import com.service.external.oa.HrService;

import localhost.services.hrmservice.HrmServiceStub.UserBean;

@Service("OaScheduleService")
public class OaScheduleService {

	static final Logger logger = LoggerFactory.getLogger(OaScheduleService.class);

	@Autowired
	FileDao fileDao;
	@Autowired
	CreateMailService createMailService;
	@Autowired
	HrService hrService;

	@Value("${filepath}")
	String filePathString;
	@Value("${server.url}")
	String serverUrlString;
	@Autowired
	PlanDao planDao;
	@Autowired
	SysDao sysDao;

	// 发送电子邮件
	public void sendXYPlanMail() {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("status", Global.YES + "");
		hashMap.put("facCode", FactoryEnum.xy.getValue());
		hashMap.put("sendDate", DateUtils.addDays(DateUtils.getCurrentDate(), 1));
		List<PlanModel> messageModels = planDao.selectList(hashMap);
		if (messageModels.size() > 0) {
			String fileId = UUID.randomUUID().toString();
			createOaFile(messageModels, fileId, FactoryEnum.xy.getName());
			List<String> userList = getUsers(FactoryEnum.xy.getValue());
			createMailService.CreateContract(messageModels, userList, "1", fileId, FactoryEnum.xy.getName());
		}
	}

	public void CreateContract(List<PlanModel> messageModels, List<String> userList) {
		String fileId = UUID.randomUUID().toString();
		createOaFile(messageModels, fileId, FactoryEnum.xy.getName());
		createMailService.CreateContract(messageModels, userList, "1", fileId, FactoryEnum.xy.getName());
	}

	// 发送电子邮件
	public void sendSPPlanMail() {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("status", Global.YES + "");
		hashMap.put("facCode", FactoryEnum.sp.getValue());
		hashMap.put("sendDate", DateUtils.addDays(DateUtils.getCurrentDate(), 1));
		List<PlanModel> messageModels = planDao.selectList(hashMap);
		if (messageModels.size() > 0) {
			String fileId = UUID.randomUUID().toString();
			createOaFile(messageModels, fileId, FactoryEnum.sp.getName());
			List<String> userList = getUsers(FactoryEnum.sp.getValue());
			createMailService.CreateContract(messageModels, userList, "1", fileId, FactoryEnum.sp.getName());
		}
	}

	// 发送电子邮件
	public void sendHKPlanMail() {
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("status", Global.YES + "");
		hashMap.put("facCode", FactoryEnum.hk.getValue());
		hashMap.put("sendDate", DateUtils.addDays(DateUtils.getCurrentDate(), 1));
		List<PlanModel> messageModels = planDao.selectList(hashMap);
		if (messageModels.size() > 0) {
			String fileId = UUID.randomUUID().toString();
			createOaFile(messageModels, fileId, FactoryEnum.hk.getName());
			List<String> userList = getUsers(FactoryEnum.hk.getValue());
			createMailService.CreateContract(messageModels, userList, "1", fileId, FactoryEnum.hk.getName());
		}
	}

	// 获取各部门用户oaid
	public List<String> getUsers(String facString) {
		List<String> userList = new ArrayList<String>();
		List<HashMap<String, Object>> serviceHashMaps = sysDao.queryItemByRoleName(SysRoleEnum.planService.getName());
		logger.info("service:{}", serviceHashMaps);
		getOaId(serviceHashMaps, userList);

		serviceHashMaps = sysDao.queryItemByRoleName(SysRoleEnum.planTm.getName());
		logger.info("tm:{}", serviceHashMaps);
		getOaId(serviceHashMaps, userList);

		serviceHashMaps = sysDao.queryItemByRoleName(SysRoleEnum.planProd.getName());
		List<HashMap<String, Object>> fielterList = new ArrayList();
		for (HashMap<String, Object> hashMap : serviceHashMaps) {
			if (hashMap.get("btn_permission").toString().contains(facString)) {
				fielterList.add(hashMap);
			}
		}
		logger.info("prod:{}", fielterList);
		getOaId(fielterList, userList);

		serviceHashMaps = sysDao.queryItemByRoleName(SysRoleEnum.planStore.getName());
		fielterList = new ArrayList();
		for (HashMap<String, Object> hashMap : serviceHashMaps) {
			if (hashMap.get("btn_permission").toString().contains(facString)) {
				fielterList.add(hashMap);
			}
		}
		logger.info("store:{}", fielterList);
		getOaId(fielterList, userList);

		serviceHashMaps = sysDao.queryItemByRoleName(SysRoleEnum.planMail.getName());
		fielterList = new ArrayList();
		for (HashMap<String, Object> hashMap : serviceHashMaps) {
			if (hashMap.get("btn_permission").toString().contains(facString)) {
				fielterList.add(hashMap);
			}
		}
		logger.info("mail:{}", fielterList);
		getOaId(fielterList, userList);

		return userList;
	}

	public void getOaId(List<HashMap<String, Object>> serviceHashMaps, List<String> userList) {
		for (HashMap<String, Object> hashMap : serviceHashMaps) {
			if (StringUtils.isNotNull(hashMap.get("oa").toString())
					&& hashMap.get("oa").toString() != (Global.NO + "")) {
				userList.add(hashMap.get("oa").toString());
			} else {
				if (StringUtils.isNotNull(hashMap.get("wx").toString())) {
					UserBean userBean = hrService.getHrmUserInfo(hashMap.get("wx").toString());
					if (userBean != null) {
						userList.add(userBean.getUserid() + "");
					}
				}
			}
		}
	}

	/**
	 * 生成oa附件
	 * 
	 * @param inquiryResultVO
	 * @return
	 */
	private HttpResult createOaFile(List<PlanModel> messageModels, String fileId, String corp) {
		String filePath = filePathString + "/" + DateUtils.getCurrentYear() + DateUtils.getCurrentMonth();
		String fileName = filePath + "/" + fileId + "-" + corp + "排货计划"
				+ DateUtils.addDays(DateUtils.getCurrentDate(), 1) + ".xlsx";

		File dir = new File(filePath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		EasyExcel.write(fileName)
				// 这里放入动态头
				.head(head()).sheet(DateUtils.addDays(DateUtils.getCurrentDate(), 1))
				.registerWriteHandler(new EasyExcelCustomCellWriteHandler())
				// 当然这里数据也可以用 List<List<String>> 去传入
				.doWrite(data(messageModels));
		HttpResult fileHttpResult = saveFile(fileId,
				corp + "排货计划" + (DateUtils.addDays(DateUtils.getCurrentDate(), 1)));
		if (fileHttpResult.getCode() != HttpStatus.SUCCESS_CODE) {
			return HttpResult.error();
		}
		return HttpResult.ok();
	}

	// 更新数据库
	private HttpResult saveFile(String fileId, String fileName) {
//		fileService.delete(inquiryResultVO.getResId());
		FileModel fileModel = new FileModel();
		fileName += ".xlsx";
		fileModel.setFileName(fileName);
		fileModel.setFileId(fileId);
		fileModel.setFileUrl(DateUtils.getCurrentYear() + DateUtils.getCurrentMonth());
		fileModel.setFileTable("tm_plan");
		fileModel.setFileRow(fileId);

		if (fileDao.update(fileModel) == 0) {
			fileDao.insert(fileModel);
		}

		return HttpResult.ok();
	}

	private List<List<String>> data(List<PlanModel> messageModels) {
		List<List<String>> list = new ArrayList<List<String>>();
		for (PlanModel programMm : messageModels) {
			List<String> childList = new ArrayList<String>();
			childList.add(TmPlanStatusEnum.getEnumName(programMm.getStatus()));
			childList.add(programMm.getSendDate());
			childList.add(programMm.getPlanCode());
			childList.add(programMm.getPlanName());
			childList.add(programMm.getOrdName());
			childList.add(programMm.getCusName());
			childList.add(programMm.getProName());
			childList.add(programMm.getPlanOrdRemark());
			childList.add(programMm.getPlanSendRemark());
			childList.add(programMm.getProNum() + "");
			childList.add(programMm.getPakModeName());
			childList.add(programMm.getPak1Name());
			if (programMm.getPak1Num() != null && programMm.getPak1Num().compareTo(new BigDecimal(0)) > 0) {
				childList.add(programMm.getPak1Num() + "");
				BigDecimal bigDecimal1000 = new BigDecimal(1000);
				childList.add((programMm.getProNum().multiply(bigDecimal1000).divide(programMm.getPak1Num())
						.setScale(BigDecimal.ROUND_CEILING)) + "");
			} else {
				childList.add("1");
				childList.add("");
			}
			childList.add(programMm.getPak2Name());
			if (programMm.getPak2Num() != null && programMm.getPak2Num().compareTo(new BigDecimal(0)) > 0) {
				childList.add(programMm.getPak2Num() + "");
			} else {
				childList.add("");
			}
			childList.add(programMm.getPlanCheckNum());
			childList.add(programMm.getDraCreatorName());
			childList.add(programMm.getDeptName());
			childList.add(programMm.getPlanIsWeight().equals(Global.YES + "") ? "是" : "否");
			childList.add(programMm.getDraTransportName());
			childList.add(programMm.getFacName());
			childList.add(programMm.getConFactoryName());
			childList.add(programMm.getStoName());
			childList.add(programMm.getCreateName());
			childList.add(programMm.getForeignName());
			childList.add(programMm.getPlanReceiveRemark());
			childList.add(programMm.getPlanReceiveTel());
			list.add(childList);
		}
		return list;
	}

	private List<List<String>> head() {
		List<List<String>> list = new ArrayList<List<String>>();

		List<String> head0 = new ArrayList<String>();

		head0 = new ArrayList<String>();
		head0.add("状态");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("预计发货日期");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("排货计划编号");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("排货计划名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("订单类型");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("客户名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("产品名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("排货计划备注");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("送货单备注");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("发货数量(吨)");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("包装方式");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("包装物名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("包装物数量");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("单桶重量(kg)");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("包装物2名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("包装物2数量");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("批号");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("业务员名称");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("业务员部门");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("是否控重");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("运输方式");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("发货工厂");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("合同工厂");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("发货仓库");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("创建人");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("外贸术语");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("收货地址");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("收货电话");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("发货罐号");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("取样数量");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("检验计划");
		list.add(head0);

		head0 = new ArrayList<String>();
		head0.add("连续灌装");
		list.add(head0);

		return list;
	}

}
